package bootstrap

import (
	"flag"
	"github.com/fsnotify/fsnotify"
	"github.com/sirupsen/logrus"
	"log"
	"mall-portalv2/conf"
	"mall-portalv2/global"
	"mall-portalv2/library/zaplogger"
	"runtime"
)

/**
* Author: joker
* TODO: test
* Date: 2022/8/17
* Time: 下午5:15
**/

var (
	ConfigPath string
)

func FlagConf() error {
	/**
	 * @Author demon
	 * @Description //TODO: 配置路径
	 * @Date 2020-7-12 16:25:31
	 **/
	flag.StringVar(&ConfigPath, "c", "config/config.json", "配置文件路径")
	flag.Parse()
	log.Printf("读取到的配置路径为:%s", ConfigPath)
	if ConfigPath == "" {
		ConfigPath = "config/config.json"
	}
	var err error
	global.Viper, err = conf.InitConf(ConfigPath)
	if err != nil {
		panic(err)
	}
	// Watch file
	global.Viper.OnConfigChange(func(e fsnotify.Event) {
		//reload
		//logrus.Println("Config file changed: config reload", e.Name)
		go func() {
			if err := global.Viper.Unmarshal(&conf.Config); err != nil {
				logrus.Fatal("无法映射数据结构体, 错误信息为: ", err)
				runtime.Goexit()
			}
			InitZap()
			logrus.Info("reloaded config......", conf.Config.Zap.Level)
		}()
	})
	global.Viper.WatchConfig()
	return err
}

func InitZap() error {
	/**
	 * @Author demon
	 * @Description //TODO: 初始化Zap的日志服务
	 * @Date 2020-7-12 16:25:31
	 **/

	//var level zapcore.Level
	config := zaplogger.ZapConfig{
		Level:         conf.Config.Zap.Level,
		Format:        conf.Config.Zap.Format,
		AppName:       conf.Config.System.AppName,
		AppVersion:    conf.Config.System.AppVersion,
		Director:      conf.Config.Zap.Director,
		LinkName:      conf.Config.Zap.LinkName,
		EncodeLevel:   conf.Config.Zap.EncodeLevel,
		StacktraceKey: conf.Config.Zap.StacktraceKey,
		LogInConsole:  conf.Config.Zap.LogInConsole,
	}
	if conf.Config.System.Debug {
		config.Level = "debug"
	}
	templog := zaplogger.NewZap(&config)
	global.Log = templog
	return nil
}
